package 回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _47_全排列II {
    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] isUsed = new boolean[nums.length];
        Arrays.sort(nums);
        List<Integer> temp = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();

        backtrack(isUsed, nums,temp,res,0,0);
        return res;
    }

    private void backtrack(boolean[] isUsed, int[] nums, List<Integer> temp, List<List<Integer>> res, int begin, int level) {
        if (level == nums.length) {
            res.add(new ArrayList<>(temp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (isUsed[i]) continue;
            // if (level > begin && i > 0 && nums[i] == nums[i - 1]) continue;
            if(i > 0 && nums[i] == nums[i - 1] && isUsed[i - 1]) {
                break;
            }
            temp.add(nums[i]);
            isUsed[i] = true;
            backtrack(isUsed, nums,temp,res,i + 1,level + 1);
            isUsed[i] = false;
            temp.remove(temp.size() - 1);
        }
    }
}
